package hamsterpolice.todo.data;

import android.content.Context;
import android.database.sqlite.*;
import android.util.Log;

public class ToDoListOpenHelper extends SQLiteOpenHelper {

	public static final String TAG = "TodoListOpenHelper";
	public static final String DB_NAME = "todolist.db";
	public static int DB_VERSION = 6;

	private ToDoListOpenHelper(Context context) {
		super(context, DB_NAME, null, DB_VERSION);
	}

	protected void finalize() throws Throwable {
		if (database != null)
			database.close();
		if (helper != null)
			helper.close();
	}

	private static ToDoListOpenHelper helper = null;
	private static SQLiteDatabase database = null;

	public static ToDoListOpenHelper getInstance(Context context) {
		if (helper == null) {
			helper = new ToDoListOpenHelper(context);
		}

		return helper;
	}
	
	@Override
	public synchronized SQLiteDatabase getWritableDatabase() {
		if(database==null){
			database = super.getWritableDatabase();
		}
		
		return database;
	}

	public void onCreate(SQLiteDatabase db) {
		UserTable.create(db);
		CategoryTable.create(db);
		ToDoListTable.create(db);
	}

	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		Log.i(TAG, String.format("Upgrading from version %s to version %s",
				oldVersion, newVersion));
		UserTable.upgrade(db, oldVersion, newVersion);
		CategoryTable.upgrade(db, oldVersion, newVersion);
		ToDoListTable.upgrade(db, oldVersion, newVersion);
	}
}
